package com.cyf.cityguidance.service.impl;

import com.cyf.cityguidance.network.bean.*;
import com.cyf.cityguidance.service.CityguidanceService;
import com.cyf.cityguidance.service.bean.NetworkPostLedInfo;
import com.cyf.db.bean.CityguidanceDtu;
import com.cyf.db.bean.CityguidanceLed;
import com.cyf.db.bean.LocalParking;
import com.cyf.db.bean.Parking;
import com.cyf.db.mapper.*;
import com.cyf.util.HttpsUtil;
import com.cyf.util.ObjectMapperUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by cheyifu on 2018/2/6.
 */
@Service
public class CityguidanceServiceImpl implements CityguidanceService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    CityguidanceDtuMapper cityguidanceDtuMapper;
    @Autowired
    LocalParkingMapper localParkingMapper;
    @Autowired
    CityguidanceLedParkingMapper ledParkingMapper;
    @Autowired
    CityguidanceLedMapper cityguidanceLedMapper;
    @Autowired
    ParkingMapper parkingMapper;

    @Override
    public CarInOutParkingRsp carInOutParking(CarInOutParkingReq req) {

        CarInOutParkingRsp rsp = new CarInOutParkingRsp();
        rsp.setResult(GuidanceBusinessRsp.FAIL);

        try {
            //根据code查找DTU信息
            CityguidanceDtu dtu = cityguidanceDtuMapper.getParkingIdByCode(req.getCode());
            if (dtu == null) {
                logger.error("查找DTU失败");
                rsp.setStrError("查找DTU失败");
                return rsp;
            }

            //检测车场是否存在
//            List<LocalParking>  parkingList = localParkingMapper.getParkingById(dtu.getParkingId());
            Parking existParking = parkingMapper.getParkingById(dtu.getParkingId());
            if (existParking == null) {
                logger.error("更改车场剩余车位数异常，车场不存在");
                rsp.setStrError("车场不存在");
                return rsp;
            }

            //剩余停车位
            Integer remainSpace = parkingMapper.getParkingSpace(dtu.getParkingId());
            //总车位
            Integer parkingSpace = parkingMapper.getParkingAllCarport(dtu.getParkingId());
            if (remainSpace == null) {
                remainSpace = parkingSpace;
            }

            if (dtu.getInoutType() == CarInOutParkingReq.INOUTTYPE_IN) {//入场
                remainSpace--;
                if (remainSpace < 0) {
                    remainSpace = 0;
                }
            } else if (dtu.getInoutType() == CarInOutParkingReq.INOUTTYPE_OUT) {//出场
                remainSpace++;
                if (remainSpace > parkingSpace) {
                    remainSpace = parkingSpace;
                }
            }
            //更新车场剩余停车位
            parkingMapper.updateParkingSpace(dtu.getParkingId(),remainSpace);

            //向LED显示屏发送消息
            //根据车场id查找所有的LED显示屏
            List<CityguidanceLed> ledList = ledParkingMapper.getLedByParkingId(dtu.getParkingId());


            //遍历LED显示屏id
            for (CityguidanceLed led : ledList) {
                //统计显示屏关联的车场数量
                int spaceTotalCount = 0;
                List<Integer> parkingIdList = ledParkingMapper.getParkingIdByLedId(led.getId());
                for (Integer parkId : parkingIdList) {
                    //剩余停车位
                    Integer carPort = parkingMapper.getParkingSpace(parkId);
                    if (carPort == null) {
                        carPort = 0;
                    }
                    spaceTotalCount += carPort;
                }

                //更新led剩余车位数
                cityguidanceLedMapper.updateCarPort(led.getId(),spaceTotalCount);
                //查找关联的DTU的id
                String dtuId = cityguidanceLedMapper.getDtuIdByLedId(led.getId());

                NetworkPostLedInfo info = new NetworkPostLedInfo();
                info.setText(String.valueOf(spaceTotalCount));
                info.setLedid(led.getAreaId());
                info.setDtuid(dtuId);
                if (led.getColor() == CarInOutParkingReq.BOTH_COLOR) {//方案三：显示两种颜色
                    if (spaceTotalCount == 0) {
                        info.setColor(CarInOutParkingReq.RED_COLOR);
                    } else {
                        info.setColor(CarInOutParkingReq.GREEN_COLOR);
                    }
                } else {
                    info.setColor(led.getColor());
                }
                //更新LED显示屏
                HttpsUtil.post(CarInOutParkingReq.INTERFACE_URL,ObjectMapperUtils.getObjectMapper().writeValueAsString(info));
            }

        } catch (Exception e) {
            logger.error("车辆出入场更新剩余车位数失败 : {}",e.getMessage());
            rsp.setStrError("服务器异常");
            return rsp;
        }

        rsp.setStrError("操作成功");
        rsp.setResult(GuidanceBusinessRsp.SUCCESS);
        return rsp;
    }

    @Override
    public UpdateParkingSpaceRsp updateRemainParkingSpace(UpdateParkingSpaceReq req) {

        UpdateParkingSpaceRsp rsp = new UpdateParkingSpaceRsp();
        rsp.setResult(GuidanceBusinessRsp.FAIL);

        try {
            Parking existParking = parkingMapper.getParkingById(req.getParkingId());
            if (existParking == null) {
                logger.error("更改车场剩余车位数异常，车场不存在");
                rsp.setStrError("车场不存在");
                return rsp;
            }

            //根据车场id，统计车场车位数
            Integer parkingSpace = parkingMapper.getParkingAllCarport(req.getParkingId());
            if (req.getRemainSpace() > parkingSpace || req.getRemainSpace() < 0) {
                logger.error("更改车场剩余车位数请求参数异常");
                rsp.setStrError("参数异常");
                return rsp;
            }

            //更新车场剩余停车位
            parkingMapper.updateParkingSpace(req.getParkingId(),req.getRemainSpace());

            //向LED显示屏发送消息
            //根据车场id查找所有的LED显示屏
            List<CityguidanceLed> ledList = ledParkingMapper.getLedByParkingId(req.getParkingId());


            //遍历LED显示屏id
            for (CityguidanceLed led : ledList) {
                //统计显示屏关联的车场数量
                int spaceTotalCount = 0;
                List<Integer> parkingIdList = ledParkingMapper.getParkingIdByLedId(led.getId());
                for (Integer parkId : parkingIdList) {
                    //剩余停车位
                    Integer carPort = parkingMapper.getParkingSpace(parkId);
                    if (carPort == null) {
                        carPort = 0;
                    }
                    spaceTotalCount += carPort;
                }

                //更新led剩余车位数
                cityguidanceLedMapper.updateCarPort(led.getId(),spaceTotalCount);
                //查找关联的DTU的id
                String dtuId = cityguidanceLedMapper.getDtuIdByLedId(led.getId());

                NetworkPostLedInfo info = new NetworkPostLedInfo();
                info.setText(String.valueOf(spaceTotalCount));
                info.setLedid(led.getAreaId());
                info.setDtuid(dtuId);
                if (led.getColor() == CarInOutParkingReq.BOTH_COLOR) {//方案三：显示两种颜色
                    if (spaceTotalCount == 0) {
                        info.setColor(CarInOutParkingReq.RED_COLOR);
                    } else {
                        info.setColor(CarInOutParkingReq.GREEN_COLOR);
                    }
                } else {
                    info.setColor(led.getColor());
                }
                //更新LED显示屏
                HttpsUtil.post(CarInOutParkingReq.INTERFACE_URL,ObjectMapperUtils.getObjectMapper().writeValueAsString(info));
            }


        } catch (Exception e) {
            logger.error("更新车场剩余车位数失败 : {}",e.getMessage());
            rsp.setStrError("服务器异常");
            return rsp;
        }

        rsp.setStrError("更新成功");
        rsp.setResult(GuidanceBusinessRsp.SUCCESS);
        return rsp;
    }
}
